package com.itheima.service.impl;

import com.google.common.hash.Funnels;
import com.itheima.domain.User;
import com.itheima.domain.UserSelective;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.util.BloomFilterUtil;
import com.itheima.util.PageHelperUtil;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * @Author: auuuu4
 * @Date: 2024/07/09/11:19
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    private String likeStr(String s){
        return '%'+s+'%';
    }
    @Override
    public PageResult selectUsersSelective(UserSelective selective) {
        if(selective == null)
            return new PageResult(0,null);
        String s = selective.getName();
        if(s != null)
            selective.setName(likeStr(s));
        List<User> list = userMapper.selectUserSelective(selective);
        return new PageResult(userMapper.selectUserNumSelective(selective),list);
    }

    @Override
    public int updateUser(User user) {
        return user == null ? 0 : userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User findByEmail(String email) {
        System.out.println(email);
        if(email == null || !isUserExist(email))
            return null;
        return userMapper.selectByEmail(email);
    }

    @Override
    public PageResult selectAllUser(Integer pageNum,Integer pageSize) {
        List<User> list = PageHelperUtil.selectList(pageNum,pageSize, userMapper,"selectUsers");
        return new PageResult(userMapper.selectUserNum(),list);
    }

    @Override
    public int addUser(User user) {
        if(user == null)
            throw new IllegalArgumentException("插入的用户为 null");
        if(isUserExist(user.getEmail()))
            throw new IllegalArgumentException("用户: "+user.getEmail()+" 已经存在");
        return userMapper.insert(user);
    }

    @Override
    public User findById(int id) {
        if(id <= 0)
            throw new IllegalArgumentException("id 不合法");
        return userMapper.selectByPrimaryKey(id);
    }

    private void initUserBloomFilter(){

        BloomFilterUtil.newBloomFilter(User.class,Funnels.stringFunnel(StandardCharsets.UTF_8),2 << 10,0.01);
        List<User> list = userMapper.selectUsers();
        Class<?> clazz = User.class;
        for(User u:list){
            BloomFilterUtil.put(clazz,u.getEmail());
            System.out.println(u.getEmail());
        }

    }
    // 使用布隆过滤器根据用户 email 检测用户是否存在
    @Override
    public boolean isUserExist(String email) {
        if(!BloomFilterUtil.isFilterExist(User.class))
            initUserBloomFilter();
        return BloomFilterUtil.mightContain(User.class,email);
    }
}

